<template>
  <!-- 这个类用于进行raycasting（光线投射）。 光线投射用于进行鼠标拾取（在三维空间中计算出鼠标移过了什么物体）。 -->
  <div class="different-faces">
    <div id="scene" @click="onMouseDown"></div>
    <div
      id="label"
      ref="labelBox"
      :style="{ left: labelBox.left + 'px', top: labelBox.top + 'px' }"
    >
      {{ labelBox.info }}
    </div>
  </div>
</template>

<script>
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

let scene;
let camera;
let renderer;
let controls;

let raycaster;
let mouse;
let selectObject = null;
export default {
  data() {
    return {
      cube: null,
      labelBox: {
        left: 0,
        top: 0,
        info: "",
      },
    };
  },
  mounted() {
    this.init();
  },
  computed: {
    windowWidth() {
      return window.innerWidth - 200;
    },
  },
  methods: {
    onMouseDown(e) {
      // 将鼠标位置归一化为设备坐标。x 和 y 方向的取值范围是 (-1 to +1)
      mouse.x = ((e.clientX - 200) / this.windowWidth) * 2 - 1; //左侧导航菜单width占了200px,计算时去除
      mouse.y = -(e.clientY / window.innerHeight) * 2 + 1;

      raycaster.setFromCamera(mouse, camera);

      const intersects = raycaster.intersectObjects(this.group.children);

      // 输出选中对象
      if (intersects.length > 0) {
        this.$refs.labelBox.style.display = "block";
        selectObject = intersects[0].object;
      } else {
        this.$refs.labelBox.style.display = "none";
        selectObject = null;
      }
    },
    // 初始化
    init() {
      this.createScene(); // 创建场景
      this.createCube(); // 创建方块
      this.createLight(); // 创建光源
      this.createCamera(); // 创建相机
      this.createRender(); // 创建渲染器
      this.createControls(); // 创建控件对象
      this.render(); // 渲染
    },
    // 创建场景
    createScene() {
      scene = new THREE.Scene();
      //用于简单模拟3个坐标轴的对象.
      //红色代表 X 轴. 绿色代表 Y 轴. 蓝色代表 Z 轴.
      scene.add(new THREE.AxesHelper(20));

      raycaster = new THREE.Raycaster();
      mouse = new THREE.Vector2();
    },
    // 创建方块
    createCube() {
      const cubeGeom = new THREE.BoxGeometry(4, 4, 4);
      const sphereGeom = new THREE.SphereGeometry(2);

      this.group = new THREE.Group();
      for (let i = 0; i < 10; i++) {
        const cube = new THREE.Mesh(
          cubeGeom,
          new THREE.MeshPhongMaterial({
            color: new THREE.Color(Math.random(), Math.random(), Math.random()),
          })
        );
        cube.name = "立方体" + i;
        cube.position.set(
          Math.round(Math.random() * 30) - 15,
          Math.round(Math.random() * 30) - 15,
          Math.round(Math.random() * 30) - 20
        );
        this.group.add(cube);

        const sphere = new THREE.Mesh(
          sphereGeom,
          new THREE.MeshPhongMaterial({
            color: new THREE.Color(Math.random(), Math.random(), Math.random()),
          })
        );
        sphere.name = "球体" + i;
        sphere.position.set(
          Math.round(Math.random() * 30) - 15,
          Math.round(Math.random() * 30) - 15,
          Math.round(Math.random() * 30) - 20
        );
        this.group.add(sphere);
      }
      scene.add(this.group);
    },

    // 创建光源
    createLight() {
      // 环境光
      const ambientLight = new THREE.AmbientLight(0xffffff, 0.1); // 创建环境光
      scene.add(ambientLight); // 将环境光添加到场景

      const spotLight = new THREE.SpotLight(0xffffff); // 创建聚光灯
      spotLight.position.set(-20, 40, -10);
      spotLight.castShadow = true;
      scene.add(spotLight);
    },
    // 创建相机
    createCamera() {
      const element = document.getElementById("scene");
      // PerspectiveCamera( fov, aspect, near, far )
      camera = new THREE.PerspectiveCamera(
        35,
        element.clientWidth / element.clientHeight,
        0.1,
        1000
      );
      camera.position.set(0, 30, 30); // 设置相机位置

      camera.lookAt(new THREE.Vector3(0, 0, 0)); // 设置相机方向
      scene.add(camera);
    },
    // 创建渲染器
    createRender() {
      const element = document.getElementById("scene");
      renderer = new THREE.WebGLRenderer();
      renderer.setSize(element.clientWidth, element.clientHeight); // 设置渲染区域尺寸
      renderer.shadowMap.enabled = true; // 显示阴影
      renderer.shadowMap.type = THREE.PCFSoftShadowMap;
      renderer.setClearColor(0x3f3f3f, 1); // 设置背景颜色
      element.appendChild(renderer.domElement);
    },
    render() {
      renderer.render(scene, camera);
      requestAnimationFrame(this.render);
      if (selectObject != undefined && selectObject != null) {
        this.renderDiv(selectObject);
      }
    },
    // 创建控件对象
    createControls() {
      controls = new OrbitControls(camera, renderer.domElement);
    },
    // 更新div的位置
    renderDiv(object) {
      // 获取窗口的一半高度和宽度
      var halfWidth = this.windowWidth / 2;
      var halfHeight = window.innerHeight / 2;

      // 逆转相机求出二维坐标
      var vector = object.position.clone().project(camera);

      // 显示模型信息
      this.labelBox.left = vector.x * halfWidth + halfWidth;
      this.labelBox.top =
        -vector.y * halfHeight + halfHeight - object.position.y;
      this.labelBox.info = "name:" + object.name;
    },
  },
};
</script>
<style scoped>
.different-faces {
  width: 100%;
  height: 100%;
  position: relative;
}
#scene {
  width: 100%;
  height: 100%;
}
#label {
  position: absolute;
  padding: 10px;
  background: rgba(255, 255, 255, 0.6);
  line-height: 1;
  border-radius: 5px;
  display: none;
}
</style>

